//
//  GKRegular.swift
//  MySwiftObject
//
//  Created by anscen on 2022/3/4.
//  Copyright © 2022 wangws1990. All rights reserved.
//

import UIKit
import CommonCrypto

let rule1 = "第[0-9一二三四五六七八九十百千]*[章回].*"
let rule2 = "[0-9]{3,4}[\\s]+[\\S.]+"

class GKRegular {
    static func txtBook() ->[GKMyDownContent]{
        var listData :[GKMyDownContent] = []
        let content = file_hpp("789") ?? ""
        var rule :String = rule1
        var datas =  GKTXTHpple.getChapters(content, rule: rule)
        if datas.count <= 2{
            rule = rule2
            datas =  GKTXTHpple.getChapters(content, rule: rule)
        }
        datas.forEach { objc in
            if let txt = objc as? String{
                let title = GKTXTHpple.getRegularString(txt, rule: rule)
                var item = GKMyDownContent()
                item.chapterId = title.md5String
                item.title = title.count == 0 ? "前文" :title
                item.content = txt
                listData.append(item)
            }
        }
        return listData
    }
    static func file_hpp(_ name :String) ->String?{
        guard let path = Bundle.main.path(forResource: name, ofType: "txt") else { return nil }
        let url = URL(fileURLWithPath: path)
        if let content = try? String(contentsOf: url, encoding: .utf8){
            return content
        }
        if let content = try? String(contentsOf: url, encoding:String.Encoding(rawValue: 0x80000632)){
            return content
        }
        if let content = try? String(contentsOf: url, encoding:String.Encoding(rawValue: 0x80000631)){
            return content
        }
        return nil
    }
    static func regularTitle(content :String,rule :String) -> [String]{
        var listData :[String] = []
        let datas = regularChapterContent(text: content, rule: rule)
        let lastRange = NSRange(location: 0, length: 0)
        let title :NSString = content as NSString
        datas?.forEach({ range in
            if range.location != NSNotFound{
                let ranges = NSRange(location: lastRange.location, length: range.location - lastRange.location)
                var body = title.substring(with: ranges)
                if body.count == 0{
                    body = "\r\n"
                }
                listData.append(body)
            }
        })
        var str = title.substring(from: lastRange.location)
        if str.count == 0{
            str = "\n\r"
        }
        if str.count > 0{
            listData.append(str)
        }
        return listData
    }
    static func regularChapterContent(text :String?,rule :String?) ->[NSRange]?{
        guard let text = text else { return nil }
        guard let rule = rule else { return nil }
        var listData :[NSRange] = []
        let title :NSString = text as NSString
        let rang = title.range(of: rule, options: .regularExpression)
        if  rang.location != NSNotFound && rang.length > 0 {
            listData.append(rang)
            var rang1 = NSRange(location: 0, length: 0)
            var location = 0
            var length = 0
            while true {
                if location == 0 && length == 0{
                    location = rang.location + rang.length;
                    length = text.count - rang.location - rang.length;
                    rang1 = NSRange(location: location, length: length)
                }else{
                    location = rang1.location + rang1.length;
                    length = text.count - rang1.location - rang1.length;
                    rang1 = NSRange(location: location, length: length)
                }
                let title :NSString = text as NSString
                rang1 = title.range(of: rule, options: .regularExpression, range: rang1)
                debugPrint(rang1.location,rang1.length)
                if rang1.location == NSNotFound && rang1.length == 0{
                    break
                }else{
                    listData.append(rang1)
                }
            }
        }
        
        return listData
    }
    static func regulars(content :String,rule :String) ->String?{
        guard let regular = try? NSRegularExpression(pattern: rule, options: .allowCommentsAndWhitespace) else { return nil }
        if let result = regular.firstMatch(in: content, options: .reportProgress, range: NSRange(location: 0, length: content.count)){
            let title :NSString = content as NSString
            return title.substring(with: result.range)
        }
        return nil
    }
}
extension String{
    //去掉首尾的空格
    func stringByTrim() ->String{
        return self.trimmingCharacters(in: .whitespacesAndNewlines)
    }
    //字符串MD5加密
    var md5String: String {
        let str = self.cString(using: String.Encoding.utf8)
        let strLen = CUnsignedInt(self.lengthOfBytes(using: String.Encoding.utf8))
        let digestLen = Int(CC_MD5_DIGEST_LENGTH)
        let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
        CC_MD5(str!, strLen, result)

        let hash = NSMutableString()

        for i in 0..<digestLen {
            hash.appendFormat("%02x", result[i])
        }
        result.deallocate()
        return hash as String
    }
}
